package com.example.sqlitelearning.Service;

import com.example.sqlitelearning.Mapper.UserMapper;
import com.example.sqlitelearning.Model.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    public UserService(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    public void registerUser(String username, String password) {
        User existingUser = userMapper.findByUsername(username);
        if (existingUser != null) {
            throw new RuntimeException("用户已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));  // 加密存储
        userMapper.insertUser(user);
    }

    public String login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return "用户不存在";
        } else if (!passwordEncoder.matches(password, user.getPassword())) {  // 验证密码
            return "密码错误";
        } else {
            return "登录成功";
        }
    }
}
